import gtdom
from gtdom.widgets import TextLine, ListBox, Label, Frame
from gtdom.observing import OSimple, OList



class BookmarksModule(gtdom.Module):
    def __init__(self):
        self.o_list = OList()
        self.o_cursor = OSimple()
    
    def render(self):
        return ListBox(self.o_list, self.o_cursor)
    
    def add_bookmark(self, path):
        self.o_list.append(path)
    
    @action("Jump", keybind = "<enter>")
    def act_jump(self):
        return self.o_list[self.o_cursor.get_value()]
    
    @action("Delete", keybind = "<del>")
    def act_delete(self):
        del self.o_list[self.o_cursor.get_value()]

class SearchModule(gtdom.Module):
    def __init__(self):
        self.o_funcname = OSimple()
    
    def _render(self):
        return HLayout(
            Label("Function name:"),
            TextLine(self.o_funcname, OSimple())
        )
    
    @action("search.forward")
    def act_search_forward(self):
        pass

    @action("search.backward")
    def act_search_backward(self):
        pass

class SourceCodeModule(gtdom.Module):
    def __init__(self):
        self.o_filename = OSimple()
        self.o_source = OSimple()
        self.o_cursor = OSimple()
    
    def show_file(self, filename, linenum):
        try:
            f = open(filename, "r")
            data = f.read()
            f.close()
        except EnvironmentError:
            data = "<source unavailable>"
        
        self.o_filename.set_value(filename)
        self.o_source.set_value(data)
        #self.o_cursor.set_value()
    
    def _render(self):
        return VLayout(
            HLayout(
                Label("Filename:"),
                Label(self.o_filename),
            ),
            TextBox(self.o_source, self.o_cursor)
        )

class TraceModule(gtdom.Module):
    TITLE = "Trace"
    
    def __init__(self, o_tree):
        self.o_tree = o_tree
        self.o_cursor = OSimple()
    
    def _render(self):
        return TreeBox(self.o_tree, self.o_cursor)
    
    @action("trace/add_bookmark")
    def act_add_bookmark(self):
        notify("add_bookmark", self.o_cursor)

class TraceReaderApplication(gtdom.Application):
    TITLE = "HPTrace Reader"
    
    def __init__(self):
        self.bookmarks = BookmarksModule()
        self.source = SourceCodeModule()
        self.search = SearchModule()
        self.trace = TraceModule()
    
    def _render(self):
        return HLayout(
            VLayout(
                self.search.render(),
                self.trace.render(),
                self.source.render(),
            ),
            VLayout(
                self.bookmarks.render()
            ),
        )
    
    @action("actions.load")
    def act_load(self):
        pass
        












